import { auth } from 'utils/auth.js';
import { get, post} from 'utils/request.js';
import { config } from 'config.js';

let configs = config();
var app = getApp();
Page({
    data: {
        dataBack: false,
        popup: {
            status: false
        },
        tagDisplay: false,
        tagsHeight: '26',
        showMap: true,
        pitsShow: '352',
        toilteHeight: null,
        tags: [],
        pits: {},
        waitings: {},
        roateAnimationDataTap: {},
        downAnimationDataTap: {},
        roateAnimationData: {},
        downAnimationData: {},
        isOpen: false,
        map: {
            zoom: 14,
            markers: [],
            polyline: [],
            steps: []
        },
        currentLatitude: null,
        currentLongitude: null,
        goLatitude: null,
        goLongitude: null,
        id: null,
        womenPits: [],
        menPits: [],
        iconPathMap: {
            'green': require('../../images/com/green.png'),
            'greenSelected': require('../../images/com/green-selected.png'),

            'yellow': require('../../images/com/yellow.png'),
            'yellowSelected': require('../../images/com/yellow-selected.png'),

            'red': require('../../images/com/red.png'),
            'redSelected': require('../../images/com/red-selected.png')
        },
        iconError: require('../../images/com/error.svg'),
        onLine: true,
        noAuth: false,
        hasMobile: 0,
        isMore: 0,
        isAvailable: 1
    },
    onLoad: function (options) {

        this.setData({
            id: options.id,
            nid: options.nid,
            icontype: options.icontype
        })

        wx.setStorageSync('configToilterId', this.data.id)  //
        var roateAnimationTap = wx.createAnimation({
            transformOrigin: "50% 50%",
            timingFunction: "ease"
        })
        var downAnimationDataTap = wx.createAnimation({
            transformOrigin: "50% 50%",
            timingFunction: "ease"
        })
        var roateAnimation = wx.createAnimation({
            transformOrigin: "50% 50%",
            timingFunction: "ease"
        })
        var downAnimationData = wx.createAnimation({
            transformOrigin: "50% 50%",
            timingFunction: "ease"
        })
        this.roateAnimation = roateAnimation;
        this.downAnimationData = downAnimationData;
        this.roateAnimationTap = roateAnimationTap; //标签的动画
        this.downAnimationDataTap = downAnimationDataTap; //标签的动画
    },
    onReady(){
        this.mapCtx = wx.createMapContext('Map');
    },
    onShow(){
        var that = this;
        var wiimobile = wx.getStorageSync('wiimobile');
        var hasMobile = wiimobile ? 1 : 0;
        that.setData({
            hasMobile: hasMobile
        })
        that.loadToilets();
        var model = app.globalData.systemInfo.model; //手机型号
        console.log(model)
        if (model.indexOf('Plus') > -1) {
            that.setData({
                tagDisplay: false
            })

        } else {
            that.setData({
                tagDisplay: true
            })
        }
    },
    onRefreshTap(e){
        var that = this;
        that.setData({
            onLine: true
        });
        that.loadToilets();
    },
    onAbnorTap(e){
        wx.openSetting({
            success: function (res) {
                if (!res.authSetting["scope.userInfo"] || !res.authSetting["scope.userLocation"]) {

                }
            }
        })
    },
    loadToilets(){
        var that = this;
        var configToilterId = wx.getStorageSync('configToilterId') || ''
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                var latitude = res.latitude;
                var longitude = res.longitude;
                that.data.currentLatitude = latitude;
                that.data.currentLongitude = longitude;
                that.getData({
                    lat: that.data.currentLatitude,
                    lng: that.data.currentLongitude,
                    id: configToilterId
                }, that);

            },
            fail: function (res) {

                //关闭loading
                wx.hideLoading();
                //没有权限
                that.setData({
                    noAuth: true
                });
            }
        })

    },
    getData(obj, context){
        wx.showLoading({
            title: '加载中'
        });
        get({'path': configs.toiletDetail}, obj).then(function (res) {

            context.setData({
                dataBack: true
            });
            if (res.data.ret == 0) {
                var data = res.data.data;
                var points = [];
                if (data.routes.polyline) {
                    data.routes.polyline.map(function (el, index) {

                        var point = {
                            latitude: el.lat,
                            longitude: el.lng
                        }
                        points.push(point)
                    })
                }
                var polyline = [{
                    color: "#ffc74b",
                    points: points,
                    width: 6
                }]

                var icon_type = data.icon_type || 1;
                var tempIconPath;
                if (icon_type == 1) {
                    tempIconPath = context.data.iconPathMap.greenSelected;
                } else if (icon_type == 2) {
                    tempIconPath = context.data.iconPathMap.yellowSelected;
                } else if (icon_type == 3) {
                    tempIconPath = context.data.iconPathMap.redSelected;
                }
                if (data.routes.to) {
                    var markers = [{
                        latitude: data.routes.to.lat,  // routes不为空的时候
                        longitude: data.routes.to.lng,
                        width: 47,
                        height: 53,
                        iconPath: tempIconPath
                    }];
                } else {
                    var markers = [{
                        latitude: null,  // routes为空的时候
                        longitude: null,
                        width: 47,
                        height: 53,
                        iconPath: tempIconPath
                    }];
                }
                var menPits = data.real_status.men_pits;
                var womenPits = data.real_status.women_pits;
                var isMore = 0;
                if (data.tags.length > 4) {
                    isMore = 1;
                }
                context.setData({
                    'map.polyline': polyline,
                    'map.markers': markers,
                    'map.zoom': data.routes.zoom,
                    id: data.id,
                    name: data.name,
                    image_url: data.image_url,
                    isAi: data.is_ai,
                    tags: data.tags,
                    isMore: isMore,
                    pits: data.pits,
                    waitings: data.waiting,
                    menPits: menPits,
                    womenPits: womenPits,
                    currentLatitude: context.data.currentLatitude,
                    currentLongitude: context.data.currentLongitude,
                    goLatitude: data.loc.lat,
                    goLongitude: data.loc.lng,
                    noAuth: false,
                    onLine: true,
                    busy_status: data.busy_status,  //lxy 忙碌状态
                    odour_index: data.odour_index, //臭气指数
                    complaints_num: data.complaints_num //被投诉
                })
                context.mapCtx.moveToLocation();
                // // //关闭loading
                wx.hideLoading();
            } else if (res.data.ret == 1 && res.data.errorcode == '4000') {
                context.setData({
                    isAvailable: 0
                })
                wx.hideLoading();

                wx.showModal({
                    title: ' ',
                    content: '很抱歉，该厕所暂时不能使用已为您推荐周边其他厕所',
                    showCancel: false,
                    confirmColor: '#1abed5',
                    success: function (res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: '/pages/index/index'
                            })
                        }
                    }
                })
            }
        }, function (res) {
            //关闭loading
            wx.hideLoading();
            //有可能是参数有问题或者是网络
            context.setData({
                onLine: false,
                noAuth: false
            });
        })
    },
    pickUpTap(e){
        console.log(e.target.dataset.tagcurindex)
        var tagcurindex = e.target.dataset.tagcurindex;

        // this.data.swiper.list.map(function(el,index){
        //   if(index == tagcurindex){
        //     el.tagsChange = true;
        //   }else{
        //     el.tagsChange = false;
        //   }
        // })

        if (!this.data.isOpen) {
            this.roateAnimationTap.rotate(-180).step();
            this.downAnimationDataTap.height(65).step();
//    this.swiperItemAnimationData.height(252).step();
            //var mapHeight = this.data.mapHeight - 40;

            this.setData({
                roateAnimationDataTap: this.roateAnimationTap.export(),
                downAnimationDataTap: this.downAnimationDataTap.export(),
                tagsHeight: 68,
                //mapHeight: mapHeight,
                isOpen: true
            })

        } else {
            this.roateAnimationTap.rotate(0).step();
            this.downAnimationDataTap.height(30).step();
//    this.swiperItemAnimationData.height(232).step();
//    var mapHeight = this.data.mapHeight + 40;

            this.setData({
                roateAnimationDataTap: this.roateAnimationTap.export(),
                downAnimationDataTap: this.downAnimationDataTap.export(),
//      swiperItemAnimationData : this.swiperItemAnimationData.export(),
                tagsHeight: 26,
//      swiperItemHeight: 232,
//      swiperContainerHeight: 185,
                //  mapHeight: mapHeight,
                isOpen: false
            })

        }

    },
    pickUpTapToilet(){
        var menPitsLength = this.data.menPits.length;
        var womenPitsLength = this.data.womenPits.length;

        var length = Math.max(menPitsLength, womenPitsLength);
        var height = null;
        if (length == 0) {
            height = 120;
        }
        else if (length > 0 && length <= 4) {
            height = 170;
        } else if (length > 4 && length <= 8) {
            height = 220;
        } else if (length > 8 && length <= 12) {
            height = 306;
        } else if (length > 12 && length <= 16) {
            height = 392;
        }
        else {
            //lxy 如果男或女超过16个厕所的话 粗略计算一下其高度

            height = 392 + 68 * Math.ceil((length - 16) / 4);

        }
        if (!this.data.isOpen) {
            this.roateAnimation.rotate(-180).step();
            this.downAnimationData.height(height).step();
            this.setData({
                roateAnimationData: this.roateAnimation.export(),
                downAnimationData: this.downAnimationData.export(),
                isOpen: true,
                pitsShow: '352',
                showMap: false
            })

        } else {
            this.roateAnimation.rotate(0).step();
            this.downAnimationData.height(0).step();
            this.setData({
                roateAnimationData: this.roateAnimation.export(),
                downAnimationData: this.downAnimationData.export(),
                isOpen: false,
                pitsShow: '352',
                showMap: true
            })

        }

    },
    goNavigateTap(e){
        console.log(e)
        var that = this;
        var dataset = e.currentTarget.dataset;
        let latitude = dataset.latitude;
        let longitude = dataset.longitude;
        var currentLatitude = dataset.currentLatitude;
        var currentLongitude = dataset.currentLongitude;
        var icontype = dataset.iconType;
        var name = dataset.name;
        var id = dataset.id;
        console.log(latitude, longitude)

        wx.navigateTo({
            url: `/pages/navigate/navigate?latitude=${latitude}&longitude=${longitude}&name=${name}&currentLatitude=${currentLatitude}&currentLongitude=${currentLongitude}&icontype=${icontype}&id=${id}`
        })
    },
    showVersion: function () {
        var that = this;
        that.setData({
            'popup.status': true
        })
        return false;
    },
    getPhoneNumber: function (e) {
        // console.log(e.detail.errMsg)
        // console.log(e.detail.iv)
        // console.log(e.detail.encryptedData);
        var mobile = e.detail.encryptedData;
        var iv = e.detail.iv;
        var that = this;
        var id = e.target.dataset.id;
        var name = e.target.dataset.name;

        var wiimobile = wx.getStorageSync('wiimobile');

        if (mobile == 'getPhoneNumber:fail user deny') {

        } else {
            console.log(wiimobile + '-------------------------->')
            if (wiimobile) {
                wx.navigateTo({
                    url: `/pages/complaint/complaint?id=${id}&name=${name}`
                })
            } else {
                post({'path': configs.mobileBind}, {encrypted_data: mobile, iv: iv}).then(function (res) {
                    console.log('-------------------+++++++');
                    console.log(typeof res);
                    // // //根据返回的结果marker在地图上面
                    if (res.data.ret == 0) {
                        var outTempData = res.data;
                        var mobile = outTempData.data.mobile;
                        wx.setStorageSync('wiimobile', mobile);

                        wx.navigateTo({
                            url: `/pages/complaint/complaint?id=${id}&name=${name}`
                        })
                    } else {
                        wx.showToast({
                            title: '请求失败',
                            image: that.data.iconError
                        })
                    }


                }, function (res) {
                    wx.showToast({
                        title: '请求失败',
                        image: that.data.iconError
                    })
                })
            }
        }

    },
    goComplaintTap(e){
        var id = e.target.dataset.id;
        var name = e.target.dataset.name;
        wx.navigateTo({
            url: `/pages/complaint/complaint?id=${id}&name=${name}`
        })
    },
    hidePopup(e){
        var that = this;
        that.setData({
            'popup.status': false,
            'province_warn': 0
        })
    },
})
